package com.example.shardingjdbcdemo1.sharding;

import com.google.common.collect.Range;
import lombok.extern.slf4j.Slf4j;
import org.apache.shardingsphere.api.sharding.standard.RangeShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.RangeShardingValue;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;

@Slf4j
public class OrderCreateTimeRangeShardingAlgorithm implements RangeShardingAlgorithm<Date> {
    @Override
    public Collection<String> doSharding(Collection<String> collection, RangeShardingValue<Date> rangeShardingValue) {

        ArrayList<String> result = new ArrayList<>();

        //获取表名称
        String tb_name = rangeShardingValue.getLogicTableName() + "_";

        //获取查询时间
        Range<Date> valueRange = rangeShardingValue.getValueRange();
        Integer queryYearMonthBegin = null; // 查询开始年月
        if (valueRange.hasLowerBound()) {
            Date beginDate = valueRange.lowerEndpoint();
            queryYearMonthBegin = Integer.valueOf(String.format("%tY", beginDate) + String.format("%tm", beginDate));
        }
        Integer queryYearMonthEnd = null; // 查询结束年月
        if (valueRange.hasUpperBound()) {
            Date endDate = valueRange.upperEndpoint();
            queryYearMonthEnd = Integer.valueOf(String.format("%tY", endDate) + String.format("%tm", endDate));
        }


        //筛选需要查询的表
        for (String each : collection) {
            // 将表中的年月取出来用于判断
            String yearMonth = each.replace(tb_name, "");
            String[] yearMonthSplit = yearMonth.split("_");
            String year = yearMonthSplit[0];
            String mon = yearMonthSplit[1];
            mon = mon.length() == 1 ? "0" + mon : mon;
            Integer yearMonthInt = Integer.parseInt(year + mon); // 数据表对应年月
            // 当范围查询时为封闭区间 且表的年月在查询区间内
            if (valueRange.hasLowerBound() && valueRange.hasUpperBound()) {
                if (yearMonthInt >= queryYearMonthBegin && yearMonthInt <= queryYearMonthEnd) {
                    result.add(each);
                }
            }
            // 当范围查询时为封闭区间
            if (valueRange.hasLowerBound() && !valueRange.hasUpperBound()) {
                if (yearMonthInt >= queryYearMonthBegin) {
                    result.add(each);
                }
            }
            // 当范围查询时为封闭区间
            if (!valueRange.hasLowerBound() && valueRange.hasUpperBound()) {
                if (yearMonthInt <= queryYearMonthEnd) {
                    result.add(each);
                }
            }
        }

        if (result.size() == 0) {
            log.error("查询表不存在");
            throw new IllegalArgumentException();
        }
        return result;
    }
}

